import React, { useState, useRef } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  StatusBar,
  Platform,
  ScrollView,
  Dimensions,
  Animated,
  Image
} from 'react-native'

import _ from 'lodash'
import { toJS } from 'mobx'
import { Observer, observer, useLocalObservable } from 'mobx-react-lite'

import { useStores } from '../stores'
import { Blank, SearchHeader, Snackbar, Gap, Button, BookItem } from '../views'
import { Placeholder, PlaceholderLine, Shine } from 'rn-placeholder'
import i18n from '../i18n'
import { shortly6, shortly4, shortly } from '../utils/text'
import Icon from 'react-native-vector-icons/Ionicons'
import { useNavigation } from '@react-navigation/native'

const CardPlaceholder = observer(() => {
  const { appearance: ap } = useStores()
  return (
    <View style={{ ...styles.bookCard, backgroundColor: ap.theme.surface }}>
      <Placeholder
        Animation={Shine}
      >
        <PlaceholderLine width={30} />
        <PlaceholderLine width={60} />
        <PlaceholderLine width={90} />
      </Placeholder>
    </View>
  )
})

const ArticlesPlaceholder = observer(() => {
  const { appearance: ap } = useStores()
  return (
    <View style={{ ...styles.bookCard, backgroundColor: ap.theme.surface }}>
      <Placeholder
        Animation={Shine}
      >
        <PlaceholderLine width={30} />
        <PlaceholderLine width={60} />
        <PlaceholderLine width={90} />
      </Placeholder>
    </View>
  )
})

const RecommentCard = observer(() => {
  const { appearance: ap, bookApi } = useStores()
  const navigation = useNavigation()
  const refreshAnimate = useRef(new Animated.Value(0)).current

  const states = useLocalObservable(() => ({
    books: [],
    setBooks(books) { this.books = books },

    refreshEnable: true,
    setRefreshEnable(enable) {
      const animation = () => {
        Animated.timing(refreshAnimate, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }).start()
      }
      if (!enable) animation()

      this.refreshEnable = enable
    },
  }))

  const fetch = () => {
    states.setRefreshEnable(false)
    bookApi.fetchRecommentBooks(6).then(data => {
      if (data.books.length)
        setTimeout(() => states.setBooks(_.shuffle(data.books)), 500)
    }).catch(err => {
      Snackbar.error({
        text: err.toString(),
        statusBarBackgroundColor: ap.theme.background
      })
    }).finally(() => setTimeout(() => states.setRefreshEnable(true), 500))
  }

  if (!states.books.length) {
    fetch()
    return <CardPlaceholder />
  }
  return (
    <View style={{
      ...styles.bookCard,
      backgroundColor: ap.theme.surface
    }}>
      <View style={{ alignItems: 'center', paddingTop: 6 }}>
        <Text style={{ ...styles.title, color: ap.theme.second, textAlign: 'center' }}>{i18n.t('recomment')}</Text>
        <Gap gap={4} />
        <Text style={{ ...styles.quote, color: ap.theme.weak, textAlign: 'center' }}>{i18n.t('recommentQuote')}</Text>
      </View>
      <View style={{ ...styles.doubleBookCard }}>
        {
          states.books.map(book => (
            <View key={book._id}>
              <TouchableOpacity
                style={{ paddingBottom: 3, alignItems: 'center' }}
                onPress={() => navigation.push('Book', { _id: book._id, title: book.name })}
              >
                <Image
                  source={{ uri: bookApi.getCoverUrl(book.cover) }}
                  style={[styles.doubleBookCover]} />
              </TouchableOpacity>


              <TouchableOpacity
                style={{ paddingBottom: 3, alignItems: 'center' }}
                onPress={() => navigation.push('Book', { _id: book._id, title: book.name })}
              >
                <Text style={{ ...styles.doubleBookTitle, color: ap.theme.second }}>
                  {shortly6(book.name)}
                </Text>
              </TouchableOpacity>

              {
                book.authors &&
                <View style={{ flexDirection: 'row', justifyContent: 'center', paddingBottom: 20 }}>
                  <TouchableOpacity
                    onPress={() => navigation.push('BookList', { data: book.authors[0], key: 'author' })}>
                    <Text style={{ ...styles.doubleBookAuthorTitle, color: ap.theme.second }}>
                      {shortly4(book.authors[0].name)}
                    </Text>
                  </TouchableOpacity>
                </View>
              }

            </View>
          ))
        }
      </View>

      <View style={{ alignItems: 'center' }}>
        {states.refreshEnable &&
          <TouchableOpacity
            style={{ ...styles.largeButton, backgroundColor: ap.theme.tiny, marginBottom: 6 }}
            activeOpacity={0.6}
            onPress={fetch}>
            <View style={{ paddingRight: 3 }}>
              <Icon name='refresh-outline' color={ap.theme.second} size={14} />
            </View>
            <Text style={{ color: ap.theme.second, fontSize: 14 }}>
              {i18n.t('refresh')}
            </Text>
          </TouchableOpacity>
          ||
          <View
            style={{
              ...styles.largeButton,
              backgroundColor: ap.theme.tiny,
              marginBottom: 6, opacity: 0.6,
            }}
          >
            <Animated.View style={{
              paddingRight: 3, transform: [{
                rotateZ: refreshAnimate.interpolate({
                  inputRange: [0, 1],
                  outputRange: ['0deg', '360deg']
                })
              }]
            }}>
              <Icon name='refresh-outline' color={ap.theme.second} size={14} />
            </Animated.View>
            <Text style={{ color: ap.theme.second, fontSize: 14 }}>
              {i18n.t('refresh')}
            </Text>
          </View>
        }
      </View>

    </View>
  )
})



const DailyArticlesCard = observer(() => {
  const { appearance: ap, bookApi } = useStores()
  const refreshAnimate = useRef(new Animated.Value(0)).current
  const navigation = useNavigation()

  const states = useLocalObservable(() => ({
    articles: [],
    setAricles(articles) {
      this.articles = articles
    },

    refreshEnable: true,
    setRefreshEnable(enable) {
      if (!enable) {
        console.log('animate start')
        Animated.timing(refreshAnimate, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }).start()
      }
      this.refreshEnable = enable
    }
  }))

  const fetch = () => {
    states.setRefreshEnable(false)
    bookApi.fetchDailyArticles(5).then(data => {
      if (data.articles)
        setTimeout(() => states.setAricles(data.articles), 500)
    }).catch(err => {
      Snackbar.error({ title: err.toString() })
    }).finally(() => {
      setTimeout(() => states.setRefreshEnable(true), 500)
    })
  }

  if (!states.articles.length) {
    fetch()
    return <ArticlesPlaceholder />
  }

  return (
    <View style={{ ...styles.bookCard, backgroundColor: ap.theme.surface }}>
      <View style={{ paddingBottom: 12, flexDirection: 'row' }}>
        <Text style={{ ...styles.title, color: ap.theme.second }}>{i18n.t('dailyArticle')}</Text>
        <View style={{ flex: 1, alignItems: 'flex-end' }}>
          {
            states.refreshEnable &&
            <TouchableOpacity onPress={() => fetch()}>
              <Icon name='refresh-outline' size={20} color={ap.theme.second} />
            </TouchableOpacity> ||
            <Animated.View style={{
              transform: [{
                rotate: refreshAnimate.interpolate({
                  inputRange: [0, 1],
                  outputRange: ['0deg', '360deg'],
                })
              }]
            }}>
              <Icon name='refresh-outline' size={20} color={ap.theme.second} />
            </Animated.View>
          }

        </View>
      </View>
      {
        states.articles.map(article => {
          if (article.summary) {
            return <TouchableOpacity key={article._id}
              onPress={() => navigation.push('Reader', {type: 'article', _id: article._id})}
              style={{
                paddingBottom: 12,
                paddingTop: 12,
              }}>

              <View style={{}}>
                <Text style={{ ...styles.articleTitle, color: ap.theme.primary, paddingBottom: 6 }}>
                  《{article.name}》
              </Text>
                <Text style={{ color: ap.theme.second, lineHeight: 18, fontSize: 12 }}>
                  {shortly(140, '...')(article.summary)}
                </Text>
              </View>
            </TouchableOpacity>
          }
        })
      }
    </View>
  )
})

const NewlyBookCard = observer(() => {
  const { appearance: ap, bookApi } = useStores()
  const [books, setBooks] = useState()

  if (!books) {
    bookApi.fetchNewlyBooks()
      .then(data => setBooks(data.books))
      .catch(err => Snackbar.error(err.toString()))
    return <CardPlaceholder />
  }
  return (
    <View style={{ ...styles.bookCard, backgroundColor: ap.theme.surface }}>
      <View style={{ paddingBottom: 12 }}>
        <Text style={{ ...styles.title, color: ap.theme.second }}>{i18n.t('newlyBooks')}</Text>
      </View>
      {
        books.map(book => (
          <BookItem key={book._id} needButton={false} book={book} />
        ))
      }
    </View>

  )
})

export default observer(({ navigation }) => {
  const { appearance: ap } = useStores()
  return (
    <View style={{ ...styles.container, backgroundColor: ap.theme.background }}>
      <ScrollView style={{ ...styles.mainContainer }}>
        <RecommentCard />
        <NewlyBookCard />
        <DailyArticlesCard />
      </ScrollView>
      <SearchHeader />
    </View>
  )
})

let statusBarHeight = 0
if (Platform.OS == 'ios') {
  statusBarHeight = StatusBar.currentHeight || 45
}

const styles = {
  container: {
    flex: 1,
    marginTop: statusBarHeight,
  },

  mainContainer: {
    flex: 1,
    marginTop: 52,
  },

  bookCard: {
    flex: 1,
    margin: 12,
    borderRadius: 6,
    padding: 12,
  },

  title: {
    fontSize: 18,
    // fontWeight: 'bold'
  },

  quote: {
    fontSize: 12,
  },

  doubleBookCard: {
    alignItems: 'center',
    paddingTop: 20,
    paddingBottom: 16,
    flexDirection: 'row',
    justifyContent: 'space-around',
    flexWrap: 'wrap'
  },

  doubleBookCover: {
    width: 113 * 0.83,
    height: 150 * 0.83,
    borderRadius: 6,
  },

  doubleBookTitle: {
    fontSize: 14,
  },

  doubleBookAuthorTitle: {
    fontSize: 12,
  },

  largeButton: {
    borderRadius: 7,
    justifyContent: 'center',
    flexDirection: 'row',
    alignItems: 'center',
    width: Dimensions.get('window').width * 0.9,
    paddingBottom: 10,
    paddingTop: 10,
  },

  articleTitle: {
    fontSize: 16
  }
}